<template>
    <Card>
        <Form ref="columnJson" :model="columnJson">
            <FormItem>
                <Row :gutter="16">
                    <Col span="7">
                        <Input v-model="modalName" placeholder="example: user" @on-keyup="handleSearchTable">
                            <Dropdown slot="append" trigger="click">
                                <a href="javascript:void(0)">
                                    <Icon type="umbrella" size="20">&nbsp;</Icon>
                                </a>
                                <DropdownMenu slot="list" v-for="(item, index) in models" :key="index">
                                    <DropdownItem divided style="text-align:left;">
                                        <Button type="warning" @click="handleQuery(item.tablename,item.comments)" style="padding:0px 15px;">
                                            <Icon type="load-b" size="15"></Icon>
                                            <span style="font-size:15px;">{{index+1}} : {{item.tablename}} - {{item.comments}}</span>
                                        </Button>
                                    </DropdownItem>
                                </DropdownMenu>
                            </Dropdown>
                        </Input>
                    </Col>
                    <Col span="5">
                        <Input v-model="modalCName" placeholder="例如: 用户"></Input>
                    </Col>
                    <Col span="10">
                        <!--<Button type="primary" icon="ios-cog" @click="handleSubmit('uap30')">提交(UAP3.0)</Button>-->
                        <Button type="success" icon="ios-cog" @click="handleSubmit('uap316')">提交</Button>
                        <Button type="warning" icon="plus-round" @click="handleAdd">增加</Button>
                        <!--<Button type="error" icon="android-delete">删除</Button>-->
                    </Col>
                    <Col span="2">&nbsp;</Col>
                </Row>
                <Row :gutter="16" style="margin-top:15px;">
                    <Col span="20">
                        <div style="float:left;">文件：&nbsp;</div>
                        <CheckboxGroup v-model="moduleTypes" style="float:left;">
                            <span v-for="(item, index) in templateCodes" :key="index">
                                <span style="color:white;font-weight:bolder;background-color:darkorange;" v-if="index==0 || item.relativepath.split('/')[1]!=templateCodes[index-1].relativepath.split('/')[1]">
                                    <br v-if="index>0" style="line-height: 43px;">{{item.relativepath.split('/')[1]}}<br>
                                </span>
                                <Checkbox :label="item.templateid">{{item.newfilename}}</Checkbox>
                            </span>
                        </CheckboxGroup>
                    </Col>
                    <Col span="4">&nbsp;</Col>
                </Row>
                <Row :gutter="16" style="border-bottom:1px solid #e9eaec;margin-top:22px;padding-bottom:15px;">
                    <Col span="20">
                        <div style="float:left;">方法：&nbsp;</div>
                        <CheckboxGroup v-model="functionTypes" style="float:left;">
                            <Checkbox label="findPage"></Checkbox>
                            <Checkbox label="findList"></Checkbox>
                            <Checkbox label="findById"></Checkbox>
                            <Checkbox label="save"></Checkbox>
                            <Checkbox label="remove"></Checkbox>
                            <Checkbox label="update"></Checkbox>
                            <Checkbox label="export"></Checkbox>
                            <Checkbox label="import"></Checkbox>
                        </CheckboxGroup>
                        &nbsp;
                        <span v-for="(item, index) in functionTypes2" :key="index">
                            <Input style="width:80px;margin-left:10px;margin-right:10px;" v-model="functionTypes2[index]"></Input>
                        </span>
                        <Button type="primary" shape="circle" icon="plus" size="small" @click="handleAddNewfunctionType()"></Button>
                    </Col>
                    <Col span="4">&nbsp;</Col>
                </Row>
                <br>

                <Row :gutter="8">
                    <Col span="9">&nbsp;</Col>
                    <Col span="6">
                        <Input v-model="keywords" @keyup.enter.native="handleSearch">
                            <Icon type="ios-search-strong" slot="prepend" style="padding:0px 10px;"></Icon>
                        </Input>
                    </Col>
                    <Col span="9">&nbsp;</Col>
                </Row>
                <br>

                <Row :gutter="8">
                    <Col span="4"><Input v-model="columnJson[0].columnName"></Input></Col>
                    <Col span="5"><Input v-model="columnJson[0].dataType"></Input></Col>
                    <Col span="3"><Input v-model="columnJson[0].columnLen"></Input></Col>
                    <Col span="4"><Input v-model="columnJson[0].constraintName"></Input></Col>
                    <Col span="8"><Input v-model="columnJson[0].commentName"></Input></Col>
                </Row>
            </FormItem>

            <FormItem v-for="(item, index) in columnJson" v-if="index>0" :key="index">
                <Row :gutter="8">
                    <Col span="4">
                        <Input v-model="item.columnName">
                            <Button slot="append" type="ghost" @click="handleRemove(index)"><Icon type="close"></Icon></Button>
                        </Input>
                    </Col>
                    <Col span="5">
                        <Select v-model="item.dataType">
                            <Option value=""></Option>
                            <Option value="varchar">varchar</Option>
                            <Option value="double">double</Option>
                            <Option value="year">year</Option>
                            <Option value="decimal">decimal</Option>
                            <Option value="char">char</Option>
                            <Option value="text">text</Option>
                            <Option value="int">int</Option>
                            <Option value="tinyint">tinyint</Option>
                            <Option value="bigint">bigint</Option>
                            <Option value="date">date</Option>
                            <Option value="datetime">datetime</Option>
						</Select>
                    </Col>
                    <Col span="3">
                        <Input v-model="item.columnLen"></Input>
                    </Col>
                    <Col span="4">
                        <Select v-model="item.constraintName">
                            <Option value=""></Option>
                            <Option value="PRIMARY KEY">主键</Option>
                            <Option value="UNIQUE">唯一</Option>
                            <Option value="NOT NULL">非空</Option>
						</Select>
                    </Col>
                    <Col span="8"><Input v-model="item.commentName"></Input></Col>
                </Row>
            </FormItem>

        </Form>
    </Card>
</template>

<script>
const {dialog} = require('electron').remote
const {ipcRenderer} = require('electron')
export default {
    name: 'servercode',
    data () {
        return {
            moduleTypes:[],
            functionTypes:['findPage','findList','findById','save','remove','update','export','import'],
            functionTypes2:[],
            modalName: '',
            modalCName: '',
            keywords:'',
            columnJson: [
                {columnName:'id',dataType:'int',columnLen:'11',constraintName:'PRIMARY KEY',commentName:'主键'}
                ,{columnName:'',dataType:'',columnLen:'',constraintName:'',commentName:''}
                ,{columnName:'',dataType:'',columnLen:'',constraintName:'',commentName:''}
            ],
            columnJsonBak:[
                {columnName:'id',dataType:'int',columnLen:'11',constraintName:'PRIMARY KEY',commentName:'主键'}
                ,{columnName:'',dataType:'',columnLen:'',constraintName:'',commentName:''}
                ,{columnName:'',dataType:'',columnLen:'',constraintName:'',commentName:''}
            ],
            models: [],
            modelsBak: [],
            templates: [],
            templateCodes: []
        };
    },
    methods: {
        handleSubmit (typename) {
            let self = this;

            let param = new FormData(); //创建form对象
            // console.info('JSON.stringify(self.columnJson):'+JSON.stringify(self.columnJson));
            param.append('moduleTypes',self.moduleTypes.join(","));
            let functionTypesAll = [];
            for(let i=0;i<self.functionTypes.length;i++){
              functionTypesAll.push(self.functionTypes[i]);
            }
            for(let j=0;j<self.functionTypes2.length;j++){
              if(self.functionTypes2[j]){
                functionTypesAll.push(self.functionTypes2[j]);
              }
            }
            param.append('functionTypes',functionTypesAll.join(","));
            param.append('columnJson',JSON.stringify(self.columnJson));//用户名
            param.append('modalName',self.modalName);//中文名
            param.append('modalIcon',self.modalIcon);//邮件
            param.append('modalCName',self.modalCName);//城市
            param.append('author',localStorage.getItem('account'));
            param.append('projectName',localStorage.getItem('projectname'));
            param.append('dbName',localStorage.getItem('mysqldatabase'));
            param.append('corpName',localStorage.getItem('corpName'));

            let projectName = localStorage.getItem('projectname');
            let server_url = "";
            if("ma-" == projectName.substr(0,3)){
                server_url = self.$util.server+'templates/microserviceCodeMa';
                param.append('typeName',typename+'-ma');
            }else if("ms-" == projectName.substr(0,3)){
                server_url = self.$util.server+'templates/microserviceCodeMs';
                param.append('typeName',typename+'-ms');
            }else{
                self.$Message.error({content:'项目名称有误', duration: 8});
            }

            if(server_url!=""){
                self.$axios.post(server_url, param, {
                    headers: {
                        'authorization': localStorage.getItem('authorization'),
                        "Content-Type":"multipart/form-data"
                    }
                }).then(function(response) {
                    // 这里是处理正确的回调
                    if (response.data.ok) {
                        self.$Message.success({content:'代码生成：成功！', duration: 8});
                        let download_url = self.$util.server + response.data.data;
                        console.log('download_url:'+download_url);
                        setTimeout(function(){
                            ipcRenderer.send('download', download_url+',2,'+self.modalName+','+localStorage.getItem('projectname'))
                        },3000)
                    } else {
                        self.$Message.error({content:'代码生成：失败！', duration: 8});
                    }
                }).catch(function (response) {
                    console.log(response)
                })
            }

        },
        handleAdd () {
            this.columnJson.push({
                columnName:'',
                dataType:'varchar',
                columnLen:'',
                constraintName:'',
                commentName:''
            });
            this.columnJsonBak = this.columnJson;
        },
        handleQuery (modalName,comments) {
            this.modalName = modalName
            this.modalCName = comments
            if(this.modalCName && this.modalCName.substr(this.modalCName.length-1)=='表'){
                this.modalCName = this.modalCName.substr(0,this.modalCName.length-1);
            }
            ipcRenderer.send('sendcontent',modalName)
        },
        handleRemove (index) {
            this.columnJson.splice(index,1);
            this.columnJsonBak = this.columnJson;
        },
        handleSearch () {
            let keywords = this.keywords;
            let columnJson = this.columnJsonBak;
            let new_columnJson = [];
            new_columnJson.push(columnJson[0]);//主键ID字段不作过滤
            for(let i=1;i<columnJson.length;i++){
                let columnName = columnJson[i].columnName?columnJson[i].columnName:'';
                let dataType = columnJson[i].dataType?columnJson[i].dataType:'';
                let columnLen = columnJson[i].columnLen?columnJson[i].columnLen:'';
                if(columnLen && columnLen.toString().indexOf('.')!=-1) columnLen = columnLen.toString().split('.')[0];
                let constraintName = columnJson[i].constraintName?columnJson[i].constraintName:'';
                let commentName = columnJson[i].commentName?columnJson[i].commentName:'';
                let concat_str = columnName + dataType + constraintName + commentName;
                if(concat_str.indexOf(keywords) != -1){
                    new_columnJson.push(columnJson[i]);
                }
            }
            this.columnJson = new_columnJson;
        },
        handleSearchTable () {
            let keywords = this.modalName;
            let models = this.modelsBak;
            let new_models = [];
            for(let i=0;i<models.length;i++){
                let tablename = models[i].tablename?models[i].tablename:'';
                let comments = models[i].comments?models[i].comments:'';
                let concat_str = tablename + comments + (i+1);
                if(concat_str.indexOf(keywords) != -1 && new_models.length<10){
                    new_models.push(models[i]);
                }
            }
            this.models = new_models;
        },
        handleInitTemplates(){
          let projectName = localStorage.getItem('projectname');
          let self = this;
          this.$axios.get(self.$util.server+'templates/listdata', {
            params:{
              groupname: "microservice-"+projectName.substr(0,2)
            },
            headers: {
              "authorization": localStorage.getItem("authorization"),
              "Content-Type":"application/json;charset=utf-8"
            }
          }).then(function(response) {
            if(response.data && response.data.length>0){
              self.templates = response.data;
              self.initTemplateNames();
            }
          }).catch( function(response) {
            console.log(response)
          });
        },
        getJavaModalName(modalName){
          let arr = modalName.split("_");
          let result = "";
          for(let i=0;i<arr.length;i++){
            let firstCharUpper = arr[i].substring(0,1).toUpperCase();
            let withoutFirstStr = arr[i].substring(1);
            result += firstCharUpper + withoutFirstStr;
          }
          return result;
        },
        initTemplateNames(){
          this.templateCodes = [];
          this.moduleTypes = [];
          let name = localStorage.getItem('name');
          let javaModalName = this.getJavaModalName(this.modalName);
          for(let i=0;i<this.templates.length;i++){
            // this.templateCodes.push({templateid: this.templates[i].templateid, filepath: this.templates[i].relativepath.replace(/\${name}/g,name).replace(/\${modalName}/g,javaModalName) + this.templates[i].newfilename.replace(/\${modalName}/g,javaModalName)});
            this.templateCodes.push({templateid: this.templates[i].templateid, relativepath: this.templates[i].relativepath.replace(/\${name}/g,name).replace(/\${modalName}/g,javaModalName), newfilename: this.templates[i].newfilename.replace(/\${modalName}/g,javaModalName)});
            if(this.templates[i].newfilename!='${modalName}.sql'){
              this.moduleTypes.push(this.templates[i].templateid);
            }
          }
        },
        handleAddNewfunctionType(){
          this.functionTypes2.push("");
        }
    },
    mounted () {

        //初始化模板选项
        this.handleInitTemplates();

        let projectName = localStorage.getItem('projectname');

        //清除全部消息监听
        ipcRenderer.removeAllListeners('tips', 'receivelist', 'receivecontent')
        //接收消息
        ipcRenderer.on('tips', (event, person) => {
            this.$Message.success({content: person, duration: 2})
        })
        //接收模块列表数据
        ipcRenderer.on('receivelist', (event, person) => {
            this.modelsBak = JSON.parse(person)
            this.models = [];
            let thesize = 10;
            if(!this.modelsBak || this.modelsBak.length==0) {
                thesize=0;
            }
            if(this.modelsBak && this.modelsBak.length<10) thesize=this.modelsBak.length;
            for(let i=0;i<thesize;i++){
                this.models.push(this.modelsBak[i]);
            }
        })
        //接收模块内容数据
        ipcRenderer.on('receivecontent', (event, person) => {
            this.columnJson = JSON.parse(person)
            this.columnJsonBak = this.columnJson
            this.keywords = ''
            this.initTemplateNames()
        })

        //初始化数据
        ipcRenderer.send('init',localStorage.getItem('mysqlhost')+','+localStorage.getItem('mysqluser')+','+localStorage.getItem('mysqlpassword')+','+localStorage.getItem('mysqlport')+','+localStorage.getItem('mysqldatabase')+','+localStorage.getItem('clientcodelist')+','+localStorage.getItem('servercodelist'))
    }

};
</script>
